package account

import (
	"context"
	"strconv"
	"time"

	"gozero/login/internal/biz"
	"gozero/login/internal/model"
	"gozero/login/internal/svc"
	"gozero/login/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginReq) (resp *types.LoginResp, err error) {
	// 检查用户是否存在
	userModel := model.NewUserModel(l.svcCtx.Mysql)
	u, err := userModel.FindOneByUsernameAndPassword(l.ctx, req.Username, req.Password)
	if err == sqlx.ErrNotFound {
		return nil, biz.PasswordIncorrect
	}
	if err != nil {
		l.Logger.Error(err)
		return nil, biz.DBError
	}

	//登录成功 生成token
	secret := l.svcCtx.Config.Auth.AccessSecret
	expire := l.svcCtx.Config.Auth.ExpireTime
	token, err := biz.GetJwtToken(secret, time.Now().Unix(), expire, u.Id)
	if err != nil {
		l.Logger.Error(err)
		return nil, biz.TokenError
	}
	// 将token存入redis数据库
	err = l.svcCtx.Redis.SetexCtx(l.ctx, strconv.FormatInt(u.Id, 10), "token: "+token, int(expire))
	if err != nil {
		l.Logger.Error(err)
		return nil, biz.RedisInsertError
	}
	resp = &types.LoginResp{
		Status: "ok",
		Token:  token,
	}
	return
}
